import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Date;
import java.util.Vector;

public class Main{

	private static boolean time = true;
	private static boolean ascending  = true;	
	
	public static void main(String[] args) throws IOException {

		if(args.length <2)
			System.out.println("Usage: nvp -d -o -s\n-d	path of directory containing the VMGs files\n-o	path for the output file that's going to contain fusion of VMGs\n-s	sorting order; may be one of the following: ta td where the 't' stands for time, 'a' for ascending, 'd' for descending\n	default: ta");
		else
		{
			File dir = new File(args[0]);
			File out = new File(args[1]);
			if(args.length == 3)
				if(args[2].contains("td"))
					ascending = false;
				else if(args[2].contains("ta"))
					ascending = true;
			
			
			if(!dir.isDirectory())
			{
				System.out.println("Error: the given directory is not a valid directory");
				System.exit(-1);
			}
			
			VMG[] vmgs = meltVMG(dir);
			System.out.println("Found & Parsed  "+vmgs.length+" valid VMG files on "+dir.listFiles().length+" total files");
			
			System.out.println("Writing to output file...");
			
			PrintStream old = System.out;
			System.setOut(new PrintStream(out));
			
			for(int i=0; i<vmgs.length; i++)
			{	
				System.out.println(vmgs[i].name+"	"+vmgs[i].cellphone);
				System.out.println(vmgs[i].date.toLocaleString());
				System.out.println(vmgs[i].text);
				System.out.println();
				System.out.println();
			}
			
			System.out.close();
			System.setOut(old);
			System.out.println("Done!");
			
		}

	}
	
	public static VMG[] meltVMG(File dir) throws IOException
	{
		File[] files  = dir.listFiles(new VMGFilenameFilter());
		Vector<VMG> vector = new Vector<VMG>();
		for(int i=0; i<files.length; i++)
		{
			vector.add(parseVMG(files[i]));
		}
		
		Object[] objArray = vector.toArray();
		VMG[] array = new VMG[objArray.length];
		for(int i=0; i<objArray.length; i++)
			array[i]=(VMG)objArray[i];
		
		java.util.Arrays.sort(array);
		if(!ascending)
		{
			VMG[] invertedArray = new VMG[array.length];
			for(int i=0; i<array.length; i++)
				invertedArray[i] = array[array.length-i-1];
			array  = invertedArray;
		}
		
		return array;
	}
	
	@SuppressWarnings("deprecation")
	public static VMG parseVMG(File file) throws IOException
	{
		FileInputStream fis = new FileInputStream(file);
		StringBuffer buffer = new StringBuffer();
		int temp;
		while( (temp=fis.read()) != -1)
			if(temp!= '\0')
			buffer.append((char)temp);

        String tokens = buffer.toString();
       
        //check on version; actually only version 1.1 has been tested; unless changes in the tags
        //this program should be able to parse contents correctly.
        
        if(!tokens.contains(TAGS.VERSION))
        {	System.out.println("WARNING: "+file.getName()+" file's version is not 1.1! Continue? y/n");
        	if(System.in.read() != 'y') 
        		System.exit(-1);
        }
        
        String name, tel, date_message, date, message;
        
        name = file.getName().substring(0, file.getName().indexOf('_'));
        
        //calculation of the delimiter indexes for the interesting parts
        
        if(tokens.contains(TAGS.TYPE_RECEIVED))
        	tel = tokens.substring(tokens.indexOf(TAGS.TEL_INIT)+TAGS.TEL_INIT.length(), tokens.indexOf(TAGS.TEL_END));
       	//if the message is of TYPE_SENT the delimiters fail because of the duplication
        //of the headers containing the sender's number too (usually blank)
        else
        {
        	int prev_init = tokens.indexOf(TAGS.TEL_INIT);
        	int prev_end = tokens.indexOf(TAGS.TEL_END);
        	tel = tokens.substring(tokens.indexOf(TAGS.TEL_INIT, prev_init+1)+TAGS.TEL_INIT.length(), tokens.indexOf(TAGS.TEL_END, prev_end+1));
        }
        
        date_message = tokens.substring(tokens.indexOf(TAGS.MESSAGE_INIT)+TAGS.MESSAGE_INIT.length(), tokens.indexOf(TAGS.MESSAGE_END));
                
        date = date_message.substring(0, 19);
        message = date_message.substring(20, date_message.length());
        
        Date UTCdate=new Date();
        UTCdate.setDate(Integer.parseInt(date.substring(0, 2)));
        UTCdate.setMonth(Integer.parseInt(date.substring(3, 5))-1);
        UTCdate.setYear(Integer.parseInt(date.substring(6, 10))-1900);
        UTCdate.setHours(Integer.parseInt(date.substring(11, 13)));
        UTCdate.setMinutes(Integer.parseInt(date.substring(14, 16)));
        UTCdate.setSeconds(Integer.parseInt(date.substring(17, 19)));
                
		VMG ret = new VMG(name,tel,UTCdate, message);
		
		return ret;
	}


}
